// 语音气泡
import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
import { adapt, adaptFontSize } from '../../ulits/Adapt';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';

// 语音气泡宽度计算相关常量
const VOICE_MIN_WIDTH = adapt(80); //语音最短气泡的宽度（秒数为1时）
const VOICE_MAX_WIDTH = adapt(220); //最长气泡宽度（防止太长撑坏界面）
const VOICE_MAX_SEC = 60; //每多1秒，气泡宽度增加的像素数

// 线性映射宽度，录音时长最多60秒，60秒以上宽度不再增加
function getVoiceBubbleWidth(duration: number) {
  const sec = Math.min(duration, VOICE_MAX_SEC);
  // 线性映射，1秒最小，60秒最大
  const width = VOICE_MIN_WIDTH + ((VOICE_MAX_WIDTH - VOICE_MIN_WIDTH) * (sec - 1)) / (VOICE_MAX_SEC - 1);
  return width;
}


interface Props {
  filePath: string;
  duration: number;
}

const audioRecorderPlayer = new AudioRecorderPlayer();

// 语音气泡组件
const VoiceBubble: React.FC<Props> = ({ filePath, duration }) => {
  // 点击播放语音
  const playVoice = async () => {
    try {
      audioRecorderPlayer.setVolume(1.0);
      await audioRecorderPlayer.startPlayer(filePath);
    } catch {}
  };

  return (
    <TouchableOpacity
      style={[styles.bubble, { width: getVoiceBubbleWidth(duration) }]}
      onPress={playVoice}
    >
      <Text style={{ fontSize: 18, marginRight: 6 }}>🔊</Text>
      <Text style={styles.text}>{duration ? `${duration}″` : ''}</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  bubble: {
    backgroundColor: 'rgb(149,236,105)',
    borderRadius: adapt(16),
    minWidth: adapt(80),
    maxWidth: adapt(220),
    height: adapt(55),
    marginBottom: adapt(8),
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    paddingHorizontal: adapt(10),
  },
  text: {
    color: '#fff',
    fontSize: adaptFontSize(18),
  },
});

export default VoiceBubble;